'''
The document oriented database
'''

import os
import json

class AppDatabase(object):

    def __init__(self, path):
        self.path = path
        if not os.path.exists(self.path):
            f = open(self.path, 'w')
            json.dump({}, f)
            f.close()
        
    def save(self, key, value):
        f = open(self.path, 'r')
        data = json.load(f)
        f.close()
        data[key] = value
        f = open(self.path, 'w')
        json.dump(data, f, sort_keys=True, indent=4)
        f.close()
        
    def get(self, key):
        f = open(self.path, 'r')
        data = json.load(f)
        f.close()
        try:
            return data[key]
        except KeyError:
            return ''

class DB(object):
    
    __inst = None
    
    #@private
    def __init__(self, rpc):
        self.path = os.path.expanduser('~/.lignum/db')
        self.main_path = os.path.join(self.path, 'main.json')
        if not os.path.exists(self.main_path):
            f = open(self.main_path, 'w')
            json.dump({}, f)
            f.close()
        if not os.path.exists(self.path):
            os.makedirs(self.path)
            
        rpc.register_function(self.save, 'database.documents.save')
        rpc.register_function(self.get, 'database.documents.get')
        rpc.register_function(self.get_all, 'database.documents.get_all')
            
    def save(self, key, value):
        f = open(self.main_path, 'r')
        data = json.load(f)
        f.close()
        data[key] = value
        f = open(self.main_path, 'w')
        json.dump(data, f, sort_keys=True, indent=4)
        f.close()
        
    def get_all(self):
        f = open(self.main_path, 'r')
        data = json.load(f)
        f.close()
        return data
        
    def get(self, key):
        f = open(self.main_path, 'r')
        data = json.load(f)
        f.close()
        try:
            return data[key]
        except KeyError:
            return ''
        
        
    def create_app_database(self, name):
        app_path = os.path.join(self.path, name + '.json')
        return AppDatabase(app_path)
            
    @classmethod
    def get_instance(self, rpc):
        if self.__inst == None:
            self.__inst = DB(rpc)
        return self.__inst

def start(args):
    loader = args['loader']

    router = loader.get_component('server.WSGI_Server').get_router()
    wrap = loader.get_component('utils.wrap')
    
    path, file = os.path.split(__file__)
    js_file = os.path.join(path, 'main.js')
    
    rpc = loader.get_component('rpc')
    
    db = DB.get_instance(rpc)
    loader.register_component('database.documents', db)
    
    @router.route('/database/main')
    def main(header, request, response_headers):
        with open(js_file, 'r') as f:
            js = f.read()
        return wrap(js)
    
def stop(args):
    router = loader.get_component('wsgi_server.WSGI_Server').get_router()
    router.delete_route('/database/main')
